<?php

namespace app\admin\controller\share;

use app\admin\model\share\CommonShare;
use app\admin\model\share\ShareUser;
use think\Db;
use app\common\controller\Backend;
use Exception;
use think\db\exception\DataNotFoundException;
use think\db\exception\ModelNotFoundException;
use think\exception\DbException;
use think\exception\PDOException;
use think\exception\ValidateException;
use app\common\model\User as FUser;
use think\Validate;
use app\common\library\Auth;
use app\common\model\UserChangeLog;
use app\common\model\ShareUserRoleLog;
use app\common\model\ShareConfig;
use fast\Arr;

/**
 * 分销用户
 *
 * @icon fa fa-circle-o
 */
class User extends Backend
{

    /**
     * User模型对象
     * @var \app\admin\model\share\ShareUser
     */
    protected $relationSearch = true;
    protected $model = null;
    protected $all_tuiguang = 0;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\share\ShareUser;
    }

    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            $filter = json_decode($this->request->get('filter'), true);
            $param1 = json_decode($this->request->param('filter'), 1);
            $where_agent = 'share_user.id>0';
            $where = ['is_delete'=>0];
            if (isset($filter['addtime'])) {
                $array = explode('-', $filter['addtime']);
                $begin = strtotime($array[0] . '-' . $array[1] . '-' . $array[2]);
                $end = strtotime($array[3] . '-' . $array[4] . '-' . $array[5]);
                if (!empty($where_agent)) {
                    $where_agent = $where_agent . " and share_user.addtime between " . $begin . ' and ' . "$end";
                } else {
                    $where_agent = "share_user.addtime between " . $begin . ' and ' . "$end";
                }
                unset($param1['addtime']);
            }

            if (isset($param1['user_id'])) {
                $where['user.id'] = $param1['user_id'];
                $param1['user.id'] = $param1['user_id'];
                unset($param1['user_id']);
            }

            if (isset($filter['user.mobile'])) {
                if (!empty($where_agent)) {
                    $where_agent = $where_agent . " and user.mobile like '%" . $filter['user.mobile'] . "%'";
                } else {
                    $where_agent = "user.mobile like '%" . $filter['user.mobile'] . "%'";
                }
                unset($param1['user.mobile']);
            }
            if (isset($filter['user.username'])) {
                if (!empty($where_agent)) {
                    $where_agent = $where_agent . " and user.username like '%" . $filter['user.username'] . "%'";
                } else {
                    $where_agent = "user.username like '%" . $filter['user.username'] . "%'";
                }
                unset($param1['user.username']);
            }
            if (isset($filter['user.nickname'])) {
                if (!empty($where_agent)) {
                    $where_agent = $where_agent . " and user.nickname like '%" . $filter['user.nickname'] . "%'";
                } else {
                    $where_agent = "user.nickname like '%" . $filter['user.nickname'] . "%'";
                }
                unset($param1['user.nickname']);
            }
            if (isset($filter['price'])) {
                $arr = explode(',',$filter['price']);
                if($arr[0] && $arr[1]){
                    $where_agent = $where_agent . " and  share_user.price > " . $arr[0] . " and share_user.price <".$arr[1];
                }elseif ($arr[0]){
                    $where_agent = $where_agent . " and  share_user.price > " . $arr[0];
                }elseif ($arr[1]){
                    $where_agent = $where_agent . " and share_user.price < " . $arr[1];
                }
                unset($param1['price']);
            }
            foreach ($param1 as $k => $v) {
                $where[$k] = $v;
            }
            list($where1, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                ->alias('share_user')
                ->with('user')
                ->where($where)
                ->where($where_agent)
                ->order($sort, $order)
                ->paginate($limit);

            foreach ($list as $key => &$row) {
                if (preg_match("/^1[34578]{1}\d{9}$/", $row["user"]["mobile"])) {
                    $mobile_xing = substr_replace($row["user"]["mobile"], '****', 3, 4);
                } else {
                    $mobile_xing = $row["user"]["mobile"];
                }
                if (preg_match("/^1[34578]{1}\d{9}$/", $row["user"]["username"])) {
                    $username_xing = substr_replace($row["user"]["username"], '****', 3, 4);
                } else {
                    $username_xing = $row["user"]["username"];
                }

                $row->visible(['id', 'user_id', 'role', 'addtime', 'parent_id','price','total_price', 'province_name', 'city_name', 'area_name', 'user.username', 'user.nickname', 'user.mobile', 'user.mobile_xing', 'user.username_xing']);

                $row["user"]["mobile_xing"] = $mobile_xing;
                $row["user"]["username_xing"] = $username_xing;

            }
            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }

        /**
     * 编辑
     *
     * @param $ids
     * @return string
     * @throws DbException
     * @throws \think\Exception
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if (false === $this->request->isPost()) {
            $this->view->assign('row', $row);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                $row->validateFailException()->validate($validate);
            }
            $params['province_id'] = 0;
            $params['city_id'] = 0;
            $params['area_id'] = 0;
            $params['province_name'] = '';
            $params['city_name'] = '';
            $params['area_name'] = '';
            $province = $this->request->post('province');
            $city = $this->request->post('city');
            $area = $this->request->post('area');
            if ($params['role'] == 2|| $params['role'] == 3) {
                if ($province) {
                    $params['province_id'] = $province;
                    $shopro_province = Db::name('shopro_area')->where(['id'=>$province])->find();
                    $params['province_name'] = $shopro_province['name'];
                }
                if ($city) {
                    $params['city_id'] = $city;
                    $shopro_city = Db::name('shopro_area')->where(['id'=>$city])->find();
                    $params['city_name'] = $shopro_city['name'];
                }
                if ($area) {
                    $params['area_id'] = $area;
                    $shopro_area = Db::name('shopro_area')->where(['id'=>$area])->find();
                    $params['area_name'] = $shopro_area['name'];
                }
            }
           
            $result = $row->allowField(true)->save($params);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }


      /**
     * 删除
     *
     * @param $ids
     * @return void
     * @throws DbException
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     */
    public function del($ids = null)
    {
        if (false === $this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ?: $this->request->post("ids");
        if (empty($ids)) {
            $this->error(__('Parameter %s can not be empty', 'ids'));
        }
        $pk = $this->model->getPk();
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            $this->model->where($this->dataLimitField, 'in', $adminIds);
        }
        $list = $this->model->where($pk, 'in', $ids)->select();

        $count = 0;
        Db::startTrans();
        try {
            foreach ($list as $item) {
                $item->is_delete = 1;
                $count += $item->save();
            }
            Db::commit();
        } catch (PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($count) {
            $this->success();
        }
        $this->error(__('No rows were deleted'));
    }
}